package cn.edu.sgu.www.mhxysy.formatter;

/**
 * 数字格式化类
 * @author 沐雨橙风ιε
 * @version 1.0
 */
public class NumberFormatter {

    /**
     * 将数字格式化为通过指定分隔符分割的字符串
     * @param number 待分割的数字
     * @param interval 分割间隔
     * @param seperator 分隔符
     * @return String
     */
    public static String format(Number number, int interval, String seperator) { // delimiter
        if (number.longValue() < 0) {
            throw new RuntimeException("不支持负数的格式化！");
        } else if (number.longValue() <= 999) { // 不超过3位数，直接返回
            return number.toString();
        } else {
            if (seperator == null) {
                seperator = ",";
            }

            // 将其转为字符串
            String data = number.toString();

            // 得到数字的位数
            int length = data.length();

            int count = length / 3;
            int modCount = length % 3;
            StringBuilder sb = new StringBuilder();

            int start = 0;

            if (modCount > 0) {
                sb.append(data, 0, modCount);
                sb.append(seperator);

                start += modCount;
            }

            for (int i = 1; i <= count; i++) {
                sb.append(data, start, start + interval);
                sb.append(seperator);

                start += interval;
            }

            return sb.substring(0, sb.length() - 1);
        }
    }

    /**
     * 将数字格式化为通过指定分隔符分割的字符串
     * @param number 待分割的数字
     * @param seperator 分隔符
     * @return String
     */
    public static String format(Number number, String seperator) {
        return format(number, 3, seperator);
    }

    /**
     * 将数字格式化为通过指定分隔符分割的字符串
     * @param number 待分割的数字
     * @return String
     */
    public static String format(Number number) {
        return format(number, ",");
    }

}